package com.fenghongzhang.lib_common.utils

import android.content.Context
import android.content.SharedPreferences
import android.widget.Toast
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * sp的属性委托
 */
inline fun <reified T> SharedPreferences.delegate(
    key: String? = null,
    default: T,
    isCommit: Boolean = false
): ReadWriteProperty<Any?, T>  = object : ReadWriteProperty<Any?, T> {
    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        val finalKey = key ?: property.name
        return when (default) {
            is String -> getString(finalKey, default) as T
            is Int -> getInt(finalKey, default) as T
            is Boolean -> getBoolean(finalKey, default) as T
            is Long -> getLong(finalKey, default) as T
            is Float -> getFloat(finalKey, default) as T
            is Set<*> -> getStringSet(finalKey, default as Set<String>) as T
            else -> throw IllegalArgumentException("Unsupported type: ${T::class.java.simpleName}")
        }
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        val finalKey = key ?: property.name
        with(edit()) {
            when (value) {
                is String -> putString(finalKey, value)
                is Int -> putInt(finalKey, value)
                is Boolean -> putBoolean(finalKey, value)
                is Long -> putLong(finalKey, value)
                is Float -> putFloat(finalKey, value)
                is Set<*> -> putStringSet(finalKey, value as Set<String>)
                else -> throw IllegalArgumentException("Unsupported type: ${T::class.java.simpleName}")
            }
            if (isCommit) commit() else apply()
        }
    }

}

fun Context.toast(message: String, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, message, duration).show()
}